const nodemailer = require('nodemailer')
const ejs = require('ejs')
const path = require('path')
const fs = require('fs')
const config = require('../config')

const VIEWS_PATH = path.resolve(__dirname, '../../views')

const transporter = nodemailer.createTransport(config.email)

/**
 * 发送邮件
 * @param {string} options.subject - 邮件主题
 * @param {string[]} options.to - 发送列表
 * @param {string} [options.html] - 发送内容
 * @param {string} [options.view] - 模板名
 * @param {object} [options.data] - 传递到模板的参数
 * @returns {Promise<object>}
 * **/
exports.sendEmail = (options) => {
  return new Promise((resolve, reject) => {
    const data = {
      from: 'MarkDo<lanyueos@163.com>',
      to: options.to.join(','),
      subject: options.subject,
      html: options.view
        ? ejs.render(fs.readFileSync(path.resolve(VIEWS_PATH, options.view + '.html'), 'utf8'), options.data || {})
        : options.html
    }

    console.log(data)

    transporter.sendMail(data, function (err, res) {
      if (err) return reject(err)

      resolve(res)
    })
  })
}

exports.sendRunNotify = async (msg) => {
  if (!config.runNotifyEmails && config.runNotifyEmails.length === 0) {
    console.warn('config.runNotifyEmails 未配置运行通知邮箱')

    return false
  }

  return exports.sendEmail({
    to: config.runNotifyEmails,
    subject: '【MarkDo】执行信息通知',
    html: msg
  })
}
